package com.fzu.geometa.metadata.controller;

import com.fzu.geometa.metadata.model.po.Register;
import com.fzu.geometa.metadata.service.MetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.MalformedURLException;
import java.net.URL;

@RestController
@RequestMapping("/gmd")
public class MetadataController {
    private static final String errXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<Info>Error</Info>";
    private static final String succeedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<Info>Succeed</Info>";
    @Autowired
    private MetadataService metadataService;

    @GetMapping(path = "/coverage/{coverageId}", produces = "application/xml")
    public String getCoverage(@PathVariable("coverageId") String coverageId) {
        String metadata = metadataService.getMetadata(coverageId);
        return metadata != null ? metadata : errXml;
    }

    @PostMapping(path = "/coverage/register", produces = "application/xml")
    public String register(Register register, String url) {
        boolean result;
        try {
            result = metadataService.registerMetadata(register, new URL(url));
        } catch (MalformedURLException e) {
            return errXml;
        }
        return result ? succeedXml : errXml;
    }

    @PostMapping(path = "/coverage/delete", produces = "application/xml")
    public String delete(String coverageId) {
        boolean result = metadataService.deleteMetaData(coverageId);
        return result ? succeedXml : errXml;
    }

    @GetMapping(path = "/query", produces = "application/xml")
    public String query(String coverageId, String path) {
        String result = metadataService.query(coverageId, path);
        return result != null ? result : errXml;
    }

    @PostMapping(path = "/delete", produces = "application/xml")
    public String delete(String coverageId, String path) {
        boolean result = metadataService.del(coverageId, path);
        return result ? succeedXml : errXml;
    }

    @PostMapping(path = "/add", produces = "application/xml")
    public String add(String coverageId, String path, String content, Integer seq) {
        boolean result = metadataService.add(coverageId, path, content, seq);
        return result ? succeedXml : errXml;
    }

}
